//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package org.flowable.engine.impl.bpmn.behavior;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.node.ObjectNode;

import java.util.*;

import com.hustcad.plm.pdm.user.service.TyplmUserService;
import org.apache.commons.lang3.StringUtils;
import org.flowable.bpmn.model.ExtensionElement;
import org.flowable.bpmn.model.FlowElement;
import org.flowable.bpmn.model.UserTask;
import org.flowable.common.engine.api.FlowableException;
import org.flowable.common.engine.api.FlowableIllegalArgumentException;
import org.flowable.common.engine.api.delegate.Expression;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEventType;
import org.flowable.common.engine.impl.calendar.BusinessCalendar;
import org.flowable.common.engine.impl.el.ExpressionManager;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.impl.bpmn.helper.SkipExpressionUtil;
import org.flowable.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.flowable.engine.impl.context.BpmnOverrideContext;
import org.flowable.engine.impl.persistence.entity.ExecutionEntity;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.engine.impl.util.IdentityLinkUtil;
import org.flowable.engine.impl.util.TaskHelper;
import org.flowable.identitylink.service.impl.persistence.entity.IdentityLinkEntity;
import org.flowable.task.service.TaskService;
import org.flowable.task.service.event.impl.FlowableTaskEventBuilder;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class UserTaskActivityBehavior extends TaskActivityBehavior {
    private static final long serialVersionUID = 1L;
    private static final Logger LOGGER = LoggerFactory.getLogger(UserTaskActivityBehavior.class);
    protected UserTask userTask;

    public UserTaskActivityBehavior(UserTask userTask) {
        this.userTask = userTask;
    }

    public void execute(DelegateExecution execution) {
        CommandContext commandContext = CommandContextUtil.getCommandContext();
        TaskService taskService = CommandContextUtil.getTaskService(commandContext);
        TaskEntity task = taskService.createTask();
        task.setExecutionId(execution.getId());

        FlowElement flowElement=execution.getCurrentFlowElement();
        Map<String, List<ExtensionElement>> map= flowElement.getExtensionElements();
        task.setVariable("executionstrategy",JSONObject.toJSONString(map.get("executionstrategy")));

        task.setTaskDefinitionKey(this.userTask.getId());
        String activeTaskName = null;
        String activeTaskDescription = null;
        String activeTaskDueDate = null;
        String activeTaskPriority = null;
        String activeTaskCategory = null;
        String activeTaskFormKey = null;
        String activeTaskSkipExpression = null;
        String activeTaskAssignee = null;
        String activeTaskOwner = null;
        List<String> activeTaskCandidateUsers = null;
        List<String> activeTaskCandidateGroups = null;
        ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext);
        ExpressionManager expressionManager = processEngineConfiguration.getExpressionManager();
        if (CommandContextUtil.getProcessEngineConfiguration(commandContext).isEnableProcessDefinitionInfoCache()) {
            ObjectNode taskElementProperties = BpmnOverrideContext.getBpmnOverrideElementProperties(this.userTask.getId(), execution.getProcessDefinitionId());
            activeTaskName = this.getActiveValue(this.userTask.getName(), "userTaskName", taskElementProperties);
            activeTaskDescription = this.getActiveValue(this.userTask.getDocumentation(), "userTaskDescription", taskElementProperties);
            activeTaskDueDate = this.getActiveValue(this.userTask.getDueDate(), "userTaskDueDate", taskElementProperties);
            activeTaskPriority = this.getActiveValue(this.userTask.getPriority(), "userTaskPriority", taskElementProperties);
            activeTaskCategory = this.getActiveValue(this.userTask.getCategory(), "userTaskCategory", taskElementProperties);
            activeTaskFormKey = this.getActiveValue(this.userTask.getFormKey(), "userTaskFormKey", taskElementProperties);
            activeTaskSkipExpression = this.getActiveValue(this.userTask.getSkipExpression(), "taskSkipExpression", taskElementProperties);
            activeTaskAssignee = this.getActiveValue(this.userTask.getAssignee(), "userTaskAssignee", taskElementProperties);
            activeTaskOwner = this.getActiveValue(this.userTask.getOwner(), "userTaskOwner", taskElementProperties);
            activeTaskCandidateUsers = this.getActiveValueList(this.userTask.getCandidateUsers(), "userTaskCandidateUsers", taskElementProperties);
            activeTaskCandidateGroups = this.getActiveValueList(this.userTask.getCandidateGroups(), "userTaskCandidateGroups", taskElementProperties);
        } else {
            activeTaskName = this.userTask.getName();
            activeTaskDescription = this.userTask.getDocumentation();
            activeTaskDueDate = this.userTask.getDueDate();
            activeTaskPriority = this.userTask.getPriority();
            activeTaskCategory = this.userTask.getCategory();
            activeTaskFormKey = this.userTask.getFormKey();
            activeTaskSkipExpression = this.userTask.getSkipExpression();
            activeTaskAssignee = this.userTask.getAssignee();
            activeTaskOwner = this.userTask.getOwner();
            activeTaskCandidateUsers = this.userTask.getCandidateUsers();
            activeTaskCandidateGroups = this.userTask.getCandidateGroups();
        }

        Object formKeyValue;
        String formKey;
        if (StringUtils.isNotEmpty(activeTaskName)) {
            formKey = null;

            try {
                formKeyValue = expressionManager.createExpression(activeTaskName).getValue(execution);
                if (formKeyValue != null) {
                    formKey = formKeyValue.toString();
                }
            } catch (FlowableException var25) {
                formKey = activeTaskName;
                LOGGER.warn("property not found in task name expression {}", var25.getMessage());
            }

            task.setName(formKey);
        }

        if (StringUtils.isNotEmpty(activeTaskDescription)) {
            formKey = null;

            try {
                formKeyValue = expressionManager.createExpression(activeTaskDescription).getValue(execution);
                if (formKeyValue != null) {
                    formKey = formKeyValue.toString();
                }
            } catch (FlowableException var24) {
                formKey = activeTaskDescription;
                LOGGER.warn("property not found in task description expression {}", var24.getMessage());
            }

            task.setDescription(formKey);
        }

        Object dueDate;
        if (StringUtils.isNotEmpty(activeTaskDueDate)) {
            dueDate = expressionManager.createExpression(activeTaskDueDate).getValue(execution);
            if (dueDate != null) {
                if (dueDate instanceof Date) {
                    task.setDueDate((Date)dueDate);
                } else {
                    if (!(dueDate instanceof String)) {
                        throw new FlowableIllegalArgumentException("Due date expression does not resolve to a Date or Date string: " + activeTaskDueDate);
                    }

                    formKeyValue = null;
                    String businessCalendarName;
                    if (StringUtils.isNotEmpty(this.userTask.getBusinessCalendarName())) {
                        businessCalendarName = expressionManager.createExpression(this.userTask.getBusinessCalendarName()).getValue(execution).toString();
                    } else {
                        businessCalendarName = "dueDate";
                    }

                    BusinessCalendar businessCalendar = CommandContextUtil.getProcessEngineConfiguration(commandContext).getBusinessCalendarManager().getBusinessCalendar(businessCalendarName);
                    task.setDueDate(businessCalendar.resolveDuedate((String)dueDate));
                }
            }
        }

        if (StringUtils.isNotEmpty(activeTaskPriority)) {
            dueDate = expressionManager.createExpression(activeTaskPriority).getValue(execution);
            if (dueDate != null) {
                if (dueDate instanceof String) {
                    try {
                        task.setPriority(Integer.valueOf((String)dueDate));
                    } catch (NumberFormatException var23) {
                        throw new FlowableIllegalArgumentException("Priority does not resolve to a number: " + dueDate, var23);
                    }
                } else {
                    if (!(dueDate instanceof Number)) {
                        throw new FlowableIllegalArgumentException("Priority expression does not resolve to a number: " + activeTaskPriority);
                    }

                    task.setPriority(((Number)dueDate).intValue());
                }
            }
        }

        if (StringUtils.isNotEmpty(activeTaskCategory)) {
            formKey = null;

            try {
                formKeyValue = expressionManager.createExpression(activeTaskCategory).getValue(execution);
                if (formKeyValue != null) {
                    formKey = formKeyValue.toString();
                }
            } catch (FlowableException var22) {
                formKey = activeTaskCategory;
                LOGGER.warn("property not found in task category expression {}", var22.getMessage());
            }

            task.setCategory(formKey.toString());
        }

        if (StringUtils.isNotEmpty(activeTaskFormKey)) {
            formKey = null;

            try {
                formKeyValue = expressionManager.createExpression(activeTaskFormKey).getValue(execution);
                if (formKeyValue != null) {
                    formKey = formKeyValue.toString();
                }
            } catch (FlowableException var21) {
                formKey = activeTaskFormKey;
                LOGGER.warn("property not found in task formKey expression {}", var21.getMessage());
            }

            task.setFormKey(formKey.toString());
        }

        boolean skipUserTask = false;
        if (StringUtils.isNotEmpty(activeTaskSkipExpression)) {
            Expression skipExpression = expressionManager.createExpression(activeTaskSkipExpression);
            skipUserTask = SkipExpressionUtil.isSkipExpressionEnabled(execution, skipExpression) && SkipExpressionUtil.shouldSkipFlowElement(execution, skipExpression);
        }

        TaskHelper.insertTask(task, (ExecutionEntity)execution, !skipUserTask);
        if (!skipUserTask) {
            this.handleAssignments(taskService, activeTaskAssignee, activeTaskOwner, activeTaskCandidateUsers, activeTaskCandidateGroups, task, expressionManager, execution);
            processEngineConfiguration.getListenerNotificationHelper().executeTaskListeners(task, "create");
            if (CommandContextUtil.getTaskServiceConfiguration(commandContext).getEventDispatcher().isEnabled()) {
                CommandContextUtil.getTaskServiceConfiguration(commandContext).getEventDispatcher().dispatchEvent(FlowableTaskEventBuilder.createEntityEvent(FlowableEngineEventType.TASK_CREATED, task));
            }
        } else {
            TaskHelper.deleteTask(task, (String)null, false, false, false);
            this.leave(execution);
        }

    }

    public void trigger(DelegateExecution execution, String signalName, Object signalData) {
        List<TaskEntity> taskEntities = CommandContextUtil.getTaskService().findTasksByExecutionId(execution.getId());
        Iterator var5 = taskEntities.iterator();

        TaskEntity taskEntity;
        do {
            if (!var5.hasNext()) {
                this.leave(execution);
                return;
            }

            taskEntity = (TaskEntity)var5.next();
        } while(taskEntity.isDeleted());

        throw new FlowableException("UserTask should not be signalled before complete");
    }

    protected void handleAssignments(TaskService taskService, String assignee, String owner, List<String> candidateUsers, List<String> candidateGroups, TaskEntity task, ExpressionManager expressionManager, DelegateExecution execution) {
        Object ownerExpressionValue;
        String customGroupIdentityLinkType;
        if (StringUtils.isNotEmpty(assignee)) {
            ownerExpressionValue = expressionManager.createExpression(assignee).getValue(execution);
            customGroupIdentityLinkType = null;
            if (ownerExpressionValue != null) {
                customGroupIdentityLinkType = ownerExpressionValue.toString();
            }

            if (StringUtils.isNotEmpty(customGroupIdentityLinkType)) {
                TaskHelper.changeTaskAssignee(task, customGroupIdentityLinkType);
            }
        }

        if (StringUtils.isNotEmpty(owner)) {
            ownerExpressionValue = expressionManager.createExpression(owner).getValue(execution);
            customGroupIdentityLinkType = null;
            if (ownerExpressionValue != null) {
                customGroupIdentityLinkType = ownerExpressionValue.toString();
            }

            if (StringUtils.isNotEmpty(customGroupIdentityLinkType)) {
                TaskHelper.changeTaskOwner(task, customGroupIdentityLinkType);
            }
        }

        Expression userIdExpr;
        Object value;
        List identityLinkEntities;
        List candidates;
        List groupIds;
        Iterator var19;
        String strValue;
        if (candidateGroups != null && !candidateGroups.isEmpty()) {
            var19 = candidateGroups.iterator();

            while(var19.hasNext()) {
                customGroupIdentityLinkType = (String)var19.next();
                userIdExpr = expressionManager.createExpression(customGroupIdentityLinkType);
                value = userIdExpr.getValue(execution);
                if (value != null) {
                    if (value instanceof Collection) {
                        identityLinkEntities = CommandContextUtil.getIdentityLinkService().addCandidateGroups(task.getId(), (Collection)value);
                        IdentityLinkUtil.handleTaskIdentityLinkAdditions(task, identityLinkEntities);
                    } else {
                        strValue = value.toString();
                        if (StringUtils.isNotEmpty(strValue)) {
                            candidates = this.extractCandidates(strValue);
                            groupIds = CommandContextUtil.getIdentityLinkService().addCandidateGroups(task.getId(), candidates);
                            IdentityLinkUtil.handleTaskIdentityLinkAdditions(task, groupIds);
                        }
                    }
                }
            }
        }

        if (candidateUsers != null && !candidateUsers.isEmpty()) {
            var19 = candidateUsers.iterator();

            while(var19.hasNext()) {
                customGroupIdentityLinkType = (String)var19.next();
                userIdExpr = expressionManager.createExpression(customGroupIdentityLinkType);
                value = userIdExpr.getValue(execution);
                if (value != null) {
                    if (value instanceof Collection) {
                        identityLinkEntities = CommandContextUtil.getIdentityLinkService().addCandidateUsers(task.getId(), (Collection)value);
                        IdentityLinkUtil.handleTaskIdentityLinkAdditions(task, identityLinkEntities);
                    } else {
                        strValue = value.toString();
                        if (StringUtils.isNotEmpty(strValue)) {
                            candidates = this.extractCandidates(strValue);
                            groupIds = CommandContextUtil.getIdentityLinkService().addCandidateUsers(task.getId(), candidates);
                            IdentityLinkUtil.handleTaskIdentityLinkAdditions(task, groupIds);
                        }
                    }
                }
            }
        }

        Iterator var16;
        String groupId;
        IdentityLinkEntity identityLinkEntity;
        Iterator var20;
        String groupIdentityLink;
        Expression idExpression;
        Iterator groupIdSet;
        if (this.userTask.getCustomUserIdentityLinks() != null && !this.userTask.getCustomUserIdentityLinks().isEmpty()) {
            var19 = this.userTask.getCustomUserIdentityLinks().keySet().iterator();

            label129:
            while(var19.hasNext()) {
                customGroupIdentityLinkType = (String)var19.next();
                var20 = ((Set)this.userTask.getCustomUserIdentityLinks().get(customGroupIdentityLinkType)).iterator();

                while(true) {
                    while(true) {
                        if (!var20.hasNext()) {
                            continue label129;
                        }

                        groupIdentityLink = (String)var20.next();
                        idExpression = expressionManager.createExpression(groupIdentityLink);
                        value = idExpression.getValue(execution);
                        if (value instanceof Collection) {
                            groupIdSet = ((Collection)value).iterator();

                            while(groupIdSet.hasNext()) {
                                identityLinkEntity = CommandContextUtil.getIdentityLinkService().createTaskIdentityLink(task.getId(), groupIdSet.next().toString(), (String)null, customGroupIdentityLinkType);
                                IdentityLinkUtil.handleTaskIdentityLinkAddition(task, identityLinkEntity);
                            }
                        } else {
                            groupIds = this.extractCandidates(value.toString());
                            var16 = groupIds.iterator();

                            while(var16.hasNext()) {
                                groupId = (String)var16.next();
                                identityLinkEntity = CommandContextUtil.getIdentityLinkService().createTaskIdentityLink(task.getId(), groupId, (String)null, customGroupIdentityLinkType);
                                IdentityLinkUtil.handleTaskIdentityLinkAddition(task, identityLinkEntity);
                            }
                        }
                    }
                }
            }
        }

        if (this.userTask.getCustomGroupIdentityLinks() != null && !this.userTask.getCustomGroupIdentityLinks().isEmpty()) {
            var19 = this.userTask.getCustomGroupIdentityLinks().keySet().iterator();

            label102:
            while(var19.hasNext()) {
                customGroupIdentityLinkType = (String)var19.next();
                var20 = ((Set)this.userTask.getCustomGroupIdentityLinks().get(customGroupIdentityLinkType)).iterator();

                while(true) {
                    while(true) {
                        if (!var20.hasNext()) {
                            continue label102;
                        }

                        groupIdentityLink = (String)var20.next();
                        idExpression = expressionManager.createExpression(groupIdentityLink);
                        value = idExpression.getValue(execution);
                        if (value instanceof Collection) {
                            groupIdSet = ((Collection)value).iterator();

                            while(groupIdSet.hasNext()) {
                                identityLinkEntity = CommandContextUtil.getIdentityLinkService().createTaskIdentityLink(task.getId(), (String)null, groupIdSet.next().toString(), customGroupIdentityLinkType);
                                IdentityLinkUtil.handleTaskIdentityLinkAddition(task, identityLinkEntity);
                            }
                        } else {
                            groupIds = this.extractCandidates(value.toString());
                            var16 = groupIds.iterator();

                            while(var16.hasNext()) {
                                groupId = (String)var16.next();
                                identityLinkEntity = CommandContextUtil.getIdentityLinkService().createTaskIdentityLink(task.getId(), (String)null, groupId, customGroupIdentityLinkType);
                                IdentityLinkUtil.handleTaskIdentityLinkAddition(task, identityLinkEntity);
                            }
                        }
                    }
                }
            }
        }

    }

    protected List<String> extractCandidates(String str) {
        return Arrays.asList(str.split("[\\s]*,[\\s]*"));
    }
}
